import * as Koa from 'koa'
import * as cors from '@koa/cors'
import * as bodyParser from 'koa-bodyparser'
import * as jwt from 'koa-jwt'

import logger from './log/index'
import router from './router'
import Authorization from './util/Authorization'
import { AppDataSource } from './data-source'
import { JWT_SECRET } from './util/constants'

AppDataSource.initialize()
  .then(async () => {
    const app = new Koa()

    // 注册中间件
    app.use(logger())
    app.use(cors())
    app.use(bodyParser())

    // 中间件 自定义了 401 响应，将用户验证失败的相关信息返回给浏览器
    app.use(Authorization())

    // 注册 JWT 中间件
    app.use(
      jwt({ secret: JWT_SECRET }).unless({
        // 给定path，处此之外的所有路由均需要鉴权
        path: [/^\/auth\/login/, /^\/auth\/reg/, /^\/uploads\//],
      })
    )

    // 注册需要鉴权的路由
    app.use(router.routes()).use(router.allowedMethods())

    // 运行服务器
    app.listen(3000, () => {
      console.log('服务器连接')
    })
  })
  .catch((error) => console.log(error))
